<?php

namespace App\Recharge\Api;

use App\Models\InterfaceConfiguration;
use App\Recharge\Bean\ApiNotifyDataBean;
use App\Recharge\Bean\BasicInformation;
use Illuminate\Http\Request;

class Hangzhoutongbao extends AbstractApi
{

    /**
     * @inheritDoc
     */
    public function rechargeData(BasicInformation $bean): array
    {
        $array = [
            'channel_id'    => $bean->getSupplierNum(),//商户号
            'timestamp'     => date('YmdHis'),
            'order_no'      => $bean->getOrderNo(),//订单号
            'account_no'    => $bean->getAccount(),
            'product_id'    => $bean->getGoodsId(),
            'voice_flag'    => 0,
            'buy_num'       => $bean->getRechargeNum() * $bean->getStartCharging(), //充值数量
            'sell_price'    => $bean->getUnitPrice(),//进价
            'notify_url'    => $bean->getNotifyUrl(),
        ];
        ksort($array);
        $array['sign'] = $this -> sign($array,$bean ->getSecretKey());
        return $array;
    }

    /**
     * @param array $array
     * @param string $secret_key
     * @return string
     */
    public function sign(array $array, string $secret_key){
       return md5(urldecode(http_build_query($array)). $secret_key);
    }
    /**
     * @inheritDoc
     */
    public function apiNotifyLogic(InterfaceConfiguration $api, Request $request): ApiNotifyDataBean
    {
        $status = $request->input('status', '');
        $order_sn = $request->input('order_no', '');
        return $this->apiNotifyData($order_sn, $status)->setExecute(in_array($status, ['SUCCESS', 'FAILED']))->setRechargeSuccess($status == 'SUCCESS');
    }

    /**
     * @return mixed
     */
    public function apiNotifySuccess(): mixed
    {
        return response('SUCCESS');
    }

    /**
     * @param InterfaceConfiguration $config
     * @param BasicInformation $bean
     * @return array|mixed
     */
    public function balance(InterfaceConfiguration $config, BasicInformation $bean){
        $array = [
            'timestamp' =>getMsecTime(),
            'app_id' => $bean ->getSupplierNum()
        ];
        $array['sign'] = $this->sign($array, $bean->getSecretKey());
        $res = curl_post($config -> balance_url,$array);
        $balance = json2array($res);
        if(isset($balance['balance']) && isset($balance['credit'])){
            return $balance['balance']+$balance['credit'];
        }else{
            return 0;
        }
    }
}
